package csc309;

import java.util.regex.Pattern;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpServletRequest;

public class Validator {

	public static boolean isValid(String regex, Object o) {
		if (o == null) return false;
		return (Pattern.compile(regex).matcher(o.toString()).matches());
	}

	public static boolean isValidNumber(String number, int lb, int ub) {
		if (number == null) return false;
		Integer n = getNumber(number);
		if (n != null)
			return lb <= n && n <= ub;
		return false;
	}

	public static boolean isValidNumber(String number, int size) {
		if (number == null) return false;
		return isValid("^[0-9]{" + size + "}$", number);
	}

	public static Integer getNumber(String number) {
		try {
			return Integer.parseInt(number);
		} catch (Exception e) {
			return null;
		}
	}

	public static boolean isValidDate(int year, int month, int day) {
		Calendar c = new GregorianCalendar(year, month, day);
		return c.get(Calendar.YEAR) == year && c.get(Calendar.MONTH) == month
				&& c.get(Calendar.DATE) == day;
	}

	public static boolean validFlight(HttpServletRequest request) {
		Integer day = getNumber(request.getParameter("day"));
		Integer month = getNumber(request.getParameter("month"));
		Integer year = getNumber(request.getParameter("year"));
		if (day == null || month == null || year == null) return false;
		long delta = (new GregorianCalendar(year, month, day)).getTimeInMillis() - (new GregorianCalendar().getTimeInMillis());
		
		if (delta > 0 && delta < (2*7*24*60*60*1000) && day != null && month != null && year != null) {
			return isValidDate(year, month, day) && (request.getParameter("from").equals("Toronto") || 
					                                 request.getParameter("from").equals("Montreal"));
		}
		return false;		    
	}
	
	public static boolean validSeat(HttpServletRequest request) {
		Integer month = getNumber(request.getParameter("expMonth"));
		Integer year = getNumber(request.getParameter("expYear")); // ...?
		if (month == null || year == null) return false;
		long delta = (new GregorianCalendar(2000 + year, month, 1)).getTimeInMillis() - (new GregorianCalendar().getTimeInMillis());
		
		return delta > 0 &&
		validFlight(request) &&
		isValidNumber(request.getParameter("seat"), 0, 5) &&
		isValid("^[A-Za-z]+$", request.getParameter("firstName")) &&
		isValid("^[A-Za-z]+$", request.getParameter("lastName")) &&
		isValid("^\\d{4}-?\\d{4}-?\\d{4}-?\\d{4}$", request.getParameter("ccNum")) &&
		isValidNumber(request.getParameter("expMonth"), 1, 12) &&
		isValidNumber(request.getParameter("expYear"), 2) &&
		isValid("^[a-zA-Z.,\\d\\s]+$", request.getParameter("address")) &&
		isValid("^[a-zA-Z]+$", request.getParameter("city")) &&
		isValid("^[a-zA-Z]+$", request.getParameter("province")) &&
		isValid("^[a-zA-Z]\\d[a-zA-Z][\\s-]?\\d[a-zA-Z]\\d$", request.getParameter("postalCode"));
	}
}
